﻿using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ERPStore.Extensions;

namespace ERPStore.Web.Extensions
{
	public static class OwinExtensions
	{
		public static void MapConnections(this IAppBuilder app)
		{
			var path = System.Web.HttpRuntime.BinDirectory;
			var config = new Microsoft.AspNet.SignalR.ConnectionConfiguration();

			try
			{
				var connectionTypeList = from file in System.IO.Directory.GetFiles(path, "*.dll", System.IO.SearchOption.TopDirectoryOnly)
										 let asm = System.Reflection.Assembly.LoadFrom(file)
										 where asm.FullName.IndexOf("ERPStore.") != -1
										 from type in asm.GetTypes()
										 where type.IsSubclassOf(typeof(Microsoft.AspNet.SignalR.PersistentConnection))
										 select type;

				foreach (var item in connectionTypeList)
				{
					var url = string.Format("/realtime/{0}", item.Name.Replace("Connection", ""));
					app.MapSignalR(url, item, config);
				}
			}
			catch(Exception ex)
			{
				System.Diagnostics.EventLog.WriteEntry("Application", ex.GetContent(), System.Diagnostics.EventLogEntryType.Error);
			}
		}
	}
}
